﻿var parentid = 0;
var catalogs = {};
var currentid = 0;
var oparentid = 0;
$(function() {
    var _allcatalog = $(".treemenu a");
    showCatalogs(_allcatalog);
    bindEvent1(_allcatalog);

    $("#dialog").dialog({
        autoOpen: false,
        width: 400,
        modal: false,
        resizable: false
    });

    BindCheckBoxEvent($("#btn_delete"));

    $("#lbtn_create").click(function() {
        $("#dialog").dialog("open");
        $("#dialog").dialog("option", "title", '添加目录');
        $("#btn_submit").val("添加");
        $("#txt_catalogname").val("");
        return false;
    });
    $("#btn_submit").click(function() {
        bindSubmitEvent();
    });
    $("#btn_delete").click(function() {
        bindMulDeleteEvent();
    });
    $("#lbtn_sorting").click(function() {
        $(".dg tbody").sortable();
        $(".dg tbody").sortable("option", "disabled", false);
        $(".dg tbody").sortable("option", "cursor", "move");

        $("#btn_delete").hide();
        $("#btn_save,#btn_cancel,.warning").show();
        formReady();
        return false;
    });
    $("#btn_save").click(function() {
        doSorting();
    });
    $("#btn_cancel").click(function() {
        $(".dg tbody").sortable("option", "disabled", true);

        $("#btn_delete").show();
        $("#btn_save,#btn_cancel,.warning").hide();
    });

    $(".dv_content").show();
    formReady();
});
function genarateHtml(obj) {
    var data = catalogs["cid" + parentid];
    if (data != null) {
        var newul = $("<ul/>");
        $(".dg tbody").empty();
        $.each(data, function(i, item) {
            //创建树型菜单的内容
            appendToMenu(newul, item);

            //创建Table的内容
            appendToTable(i, item);
        });
        
        if (obj.next().length == 0) {
            obj.after(newul);
        }
        else {
            obj.next().show();
        }
    }

    formReady();
}
function showCatalogs(obj) {
    if (catalogs["cid" + parentid] == null) {
        $.ajax({
            type: "GET",
            url: rootpath + "course/catalog/catalog.ashx",
            data: { type: 'getcatalogs', pid: parentid, r: Math.random() },
            dataType: "json",
            success: function(data) {
                catalogs["cid" + parentid] = data;
                genarateHtml(obj);
            }
        });
    }
    else {
        genarateHtml(obj);
    }
}
function appendToTable(i, item) {
    i++;
    var cb = "<input type='checkbox' value='" + item.cid + "' />";
    var delbutton = "&nbsp;<input type='button' class='deleteButton' rel='" + item.cid + "' />";
    if (item.totalsubs > 0 || item.totalcourses > 0) {
        cb = "";
        delbutton = "";
    }

    $(".dg tbody").append("<tr> \
                                <td>" + cb + "</td> \
                                <td>" + i + "</td> \
                                <td>" + item.cname + "</td> \
                                <td>" + item.totalcourses + "</td> \
                                <td>" + item.totalsubs + "</td> \
                                <td><input type='button' class='editButton' rel='" + item.cid + "' />" + delbutton + "</td> \
                            </tr>");
                            
    bindButtonEvent($(".editButton:last"));

    if (cb.length > 0) {
        BindCheckBox($("#btn_delete"),$(":checkbox:last"));    
    }
    if (delbutton.length > 0) {
        bindDeleteEvent($(".deleteButton:last"));
    }

    $(".dg tbody tr:last").hover(function() { $(this).addClass("tdmover"); }, function() { $(this).removeClass("tdmover"); });
}
function appendToMenu(obj, item) {
    var classname = "w";
    if (item.totalsubs > 0) {
        classname = "r";
    }
    var newli = $("<li/>");
    newli.append('<a href=\"#" class="' + classname + '" rel="' + item.cid + '">' + item.cname + '</a>');
    obj.append(newli);
    var _this = newli.find("a");
    if (item.totalsubs > 0) {
        bindEvent1(_this);
    }
    else {
        bindEvent2(_this);
    }
}
function bindEvent1(_this) {
    _this.click(function() {
        resetStatus(_this);

        $(".treemenu .current").removeClass("current");
        _this.addClass("current");

        showCatalogs(_this);
        if (_this.hasClass("r")) {
            _this.addClass("b");
            _this.removeClass("r");
        }
        else {
            _this.addClass("r");
            _this.removeClass("b");
            _this.next().hide();
        }
        return false;
    });
}
function bindEvent2(_this) {
    _this.click(function() {
        resetStatus(_this);
        $(".dg tbody").empty();
        $(".treemenu .current").removeClass("current");
        $(this).addClass("current");
        return false;
    });
}
function bindButtonEvent(_this) {
    var _tr = _this.parents("tr")
    _this.click(function() {
        $("#txt_catalogname").val(_tr.find("td").eq(2).html());
        $("#dialog").dialog("open");
        $("#dialog").dialog("option", "title", '修改目录');
        $("#btn_submit").val("修改");
        currentid = _this.attr("rel");
        oparentid = $(".treemenu .current").attr("rel");
    });
}
function resetStatus(_this) {
    if (_this) {
        parentid = _this.attr("rel");
        parentname = _this.html();
        if (parentname == "全部目录") {
            parentname = "";
        }
        $("#txt_parentname").val(parentname);
    }
    $("#cb_All").attr("checked", "");
    $("#btn_delete").attr("disabled", "diabled");
}
function bindSubmitEvent() {
    var catalogname = $('#txt_catalogname').val();
    if (catalogname.length == 0) {
        if ($('#txt_catalogname').next("span").length == 0) {
            $('#txt_catalogname').after("<span style='color:red;'>目录名称不能为空！</span>");
        }
        else {
            $('#txt_catalogname').next().show();
        }
        return;
    }

    $("#btn_submit").attr("disabled", "disabled").after("<span>提交中.....</span>");

    var data = { type: 'addcatalog', cname: catalogname, pid: parentid };
    
    if (currentid > 0) {
        data = { type: 'editcatalog', cname: catalogname, pid: parentid, cid: currentid, opid: oparentid };
    }

    $.ajax({
        type: "POST",
        url: rootpath + "course/catalog/catalog.ashx",
        data: data,
        dataType: "string",
        success: function(data) {

            if (currentid > 0) {
                if (data > 0) {
                    $("#dialog").dialog("close");
                    facebox("课程目录修改成功！");

                    $(".editButton[rel='" + currentid + "']").parents("tr").find("td").eq(2).html(catalogname);
                    $(".treemenu a[rel='" + currentid + "']").html(catalogname);

                    resetData(catalogname);

                    currentid = 0;
                    oparentid = 0;
                    $("#txt_catalogname").val("");
                }
                else if (data == -1) {
                    facebox("不能将目录移至自己的子目录！");
                }
                else {
                    facebox("课程目录修改失败！");
                }
            }
            else {
                if (data > 0) {
                    $("#dialog").dialog("close");
                    facebox("课程目录创建成功！");

                    var item = { cid: data, cname: catalogname, pid: parentid, totalsubs: 0, totalcourses: 0 };

                    addItem(parentid, item);
                    resetCache(parentid, 1);
                    resetMenu(item);
                    appendToTable($(".dg tbody tr").length, item);

                    $("#txt_catalogname").val("");
                    formReady();
                }
                else {
                    facebox("课程目录创建失败！");
                }
            }
            $("#btn_submit").attr("disabled", "").next("span").remove();
        }
    });
}
function bindMulDeleteEvent() {    
    confirmbox("确定要删除所有选中目录吗？");

    $(window.parent.document).find("#btn_sure").click(function() {
        closebox();

        var cids = "";
        $("input:checked").not("#cb_All").each(function() {
            cids += $(this).val() + ",";
        });

        doDelete(cids);
    });
}
function bindDeleteEvent(_this) {
    _this.click(function() {
        confirmbox("确定要删除当前目录吗？");
        $(window.parent.document).find("#btn_sure").click(function() {
            closebox();
            doDelete(_this.attr("rel"));
        });
    });
}
function doDelete(cids) {
    $.ajax({
        type: "POST",
        url: rootpath + "course/catalog/catalog.ashx",
        data: { type: 'deletecatalog', pid: parentid, cids: cids, r: Math.random() },
        dataType: "string",
        success: function(data) {
            if (data == 1) {
                facebox("操作已完成！");

                var _cids = cids.split(',');

                for (var i = 0; i < _cids.length; i++) {
                    var cid = _cids[i];
                    if (cid != "") {
                        removeTr(cid);
                        removeMenu(cid);
                        removeItem(cid,parentid);
                        resetCache(parentid, -1);
                    }
                }
                resetStatus();
            }
        }
    });
}
function doSorting() {
    var cids = "";
    $(".dg tbody .editButton").each(function() {
        cids += $(this).attr("rel") + ",";
    });
    $.ajax({
        type: "POST",
        url: rootpath + "course/catalog/catalog.ashx",
        data: { type: 'sorting', cids: cids, r: Math.random() },
        dataType: "string",
        success: function(data) {
            if (data == 1) {
                facebox("操作已完成！");

                $(".dg tbody").sortable("option", "disabled", true);

                $("#btn_delete").show();
                $("#btn_save,#btn_cancel,.warning").hide();

                updateSorting(cids);
                updatesequence();
            }
        }
    });
}
function removeTr(cid) {
    $(".deleteButton[rel='" + cid + "']").parents("tr").eq(0).remove();
}
function removeMenu(cid) {
    var parentli = $(".treemenu a[rel='" + cid + "']").parent();

    if (parentli.siblings().length == 0) {
        var _a = parentli.parent().prev();
        _a.removeClass("b").addClass("w").unbind("click");
        bindEvent2(_a);

        parentli.parent().remove();
    }
    else {
        parentli.remove();
    }
}
function resetData(cname) {
    var item = updateItem(oparentid, currentid, cname,null);

    resetCache(oparentid, -1);
    resetCache(parentid, 1);

    if (oparentid != parentid) {
        removeItem(currentid, oparentid);
        addItem(parentid, item);
        removeMenu(currentid);
        resetMenu(item);
        appendToTable($(".dg tbody tr").length, item);
    }
}
function resetCache(pid, val) {

    var ancestor = $(".treemenu a[rel='" + pid + "']").parents("ul").eq(0).prev().attr("rel");

    if (catalogs["cid" + ancestor] != null) {
        $.each(catalogs["cid" + ancestor], function(i, item) {
            if (item.cid == pid) {
                item.totalsubs = parseInt(item.totalsubs) + val;
            }
        });
    }
}
function resetMenu(item) {

    var _current = $(".treemenu .current");
    var newul = _current.next();

    if (newul.length == 0) {
        newul = $("<ul/>");       
        _current.after(newul).removeClass("w").addClass("b").unbind("click");
        bindEvent1(_current);
    }

    appendToMenu(newul, item);
}
function removeItem(cid,pid) {

    var newdata = [];

    $.each(catalogs["cid" + pid], function(i, item) {
        if (item.cid != cid) {
            newdata.push(item);
        }
    });
   
    catalogs["cid" + pid] = newdata;
}
function addItem(cid, item) {
    if (catalogs["cid" + parentid] == null) {
        catalogs["cid" + cid] = [];
    }
    catalogs["cid" + parentid].push(item);
}
function updateItem(pid,cid,cname,sequence) {
    var citem = {};
    var data = catalogs["cid" + pid];

    $.each(data, function(i, item) {
    if (item.cid == cid) {
            if(cname != null)
                item.cname = cname;
            if (sequence != null) {
                item.sequence = sequence;
            }
            citem = item;
        }
    });   
    return citem;
}
function updateSorting(cids) {
    var _cids = cids.split(',');
    for (var i = 0; i < _cids.length; i++) {
        var cid = _cids[i];
        if (cid != "") {            
            updateItem(parentid, cid, null, i * 10);
        }
    }
    catalogs["cid" + parentid].sort(function(a, b) { return a["sequence"] > b["sequence"] ? 1 : a["sequence"] == b["sequence"] ? 0 : -1 });

    reBuildMenu();
}
function updatesequence() {
    $(".dg tbody tr").each(function(i) {
        $(this).find("td:eq(1)").html(i + 1);
    });
}
function reBuildMenu() {
    var _ul = $(".treemenu .current").next();
    _ul.empty();
    var data = catalogs["cid" + parentid];

    $.each(data, function(i, item) {
        appendToMenu(_ul,item);
    });   
}
